package com.edais.service.imp;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.edais.actions.PerMatchDetailAction;
import com.edais.dao.PerMatchDao;
import com.edais.domain.OrderBalance;
import com.edais.domain.PerMatchCredit;
import com.edais.domain.PreMatchLoan;
import com.edais.service.PerMatchService;

@Service

@Transactional(propagation=Propagation.SUPPORTS,readOnly=true)
public class PerMatchrServiceImp implements PerMatchService {
	private static final Log logger = LogFactory.getLog(PerMatchDetailAction.class);

	@Autowired
	private PerMatchDao perMatchDao;

	/**
	 * 根据用户id、订单id、核心订单余额coreBalance，获取预匹配债权列表
	 * @param 用户id
	 * @param 订单id
	 * @param 签约中金额
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class,readOnly=false)
	public List<PerMatchCredit> getPerMatchCreditList(String userId, String orderId, BigDecimal coreBalance) throws Exception{
		List<PerMatchCredit> rtnList = new ArrayList<PerMatchCredit>();

		BigDecimal perBalance = null;   // 订单余额表中取得余额
		
//		OrderBalance domain = new OrderBalance();
//		domain.setOrderId(Integer.valueOf(orderId));
		
		// 根据订单id从【订单余额表T_ORDER_BALANCE】获取预匹配订单余额,作为预匹配金额
		OrderBalance ordarBalance = this.perMatchDao.getOrderBalanceByOrderId(Integer.valueOf(orderId));
		if (ordarBalance != null) {
			perBalance = ordarBalance.getOrderBalance();
		}
		//如果不存在记录
		if (perBalance == null) {
			try {
				ordarBalance = new OrderBalance();
				ordarBalance.setOrderId(Integer.valueOf(orderId));  // 订单id
				ordarBalance.setOrderBalance(coreBalance);          // 订单余额
				ordarBalance.setOrderState("1");                    // 是否有效：0无效，1有效
				ordarBalance.setUserId(Integer.valueOf(userId));    // 用户id
				
				// 插入预匹配订单余额记录
				this.perMatchDao.insertOrderBalanceInfo(ordarBalance);
			} catch (Exception e) {
				logger.error(e.getMessage());
				throw new Exception("PerMatchrServiceImp 插入预匹配订单余额异常----订单id：" + orderId);
			}
			
			// 签约中金额 > 0
			if(coreBalance.compareTo(BigDecimal.ZERO) == 1){
				try {
					// 根据订单id、签约中金额插入预匹配标的列表【PER_MATCH_CREDIT】（动态），并返回
					rtnList = this.getPerMatchCreditList(orderId, coreBalance);	
					
				} catch (Exception e) {
					e.printStackTrace();
					logger.error(e.getMessage());
					throw new Exception("PerMatchrServiceImp 根据订单id、签约中金额生成预匹配债权列表----订单id：" + orderId);
				}
			}
		} else {
			// 如果存在记录
				// 如果预匹配金额与签约中金额相同
			if(perBalance.compareTo(coreBalance) == 0){
				// 根据订单号取预匹配标的列表【PER_MATCH_CREDIT】（动态)
				rtnList = this.perMatchDao.getPreMatchCreditByOrderId(Integer.parseInt(orderId));
			}else{
				// 如果不相同
				try {
					// 更新预匹配余额为签约中金额
					ordarBalance.setOrderBalance(coreBalance);         // 订单余额
					this.perMatchDao.updateOrderBalanceInfoByOrderId(ordarBalance);					
				} catch (Exception e) {
					logger.error(e.getMessage());
					throw new Exception("PerMatchrServiceImp 更新预匹配余额异常----订单id：" + orderId);
				}
				
				try {
					// 根据订单id删除预匹配标的列表【PER_MATCH_CREDIT】（动态)
					this.perMatchDao.deletePerMatchCrditByOrderId(Integer.valueOf(orderId));
				} catch (Exception e) {
					logger.error(e.getMessage());
					throw new Exception("PerMatchrServiceImp 根据订单id删除预匹配债权列表----订单id：" + orderId);
				}
				
				// 签约中金额 > 0
				if(coreBalance.compareTo(BigDecimal.ZERO) == 1){
					try {
						// 根据订单id、签约中金额插入预匹配标的列表【PER_MATCH_CREDIT】（动态），并返回
						rtnList = this.getPerMatchCreditList(orderId, coreBalance);	
						
					} catch (Exception e) {
						logger.error(e.getMessage());
						throw new Exception("PerMatchrServiceImp 根据订单id、签约中金额生成预匹配债权列表----订单id：" + orderId);
					}			
				}
			}
		}
		return rtnList;
	}
	
	
	/**
	 * 根据订单id、签约中金额插入预匹配标的列表（动态），并返回
	 * @param 订单id    orderId
	 * @param 订单余额  coreBalance
	 * @return
	 */
	private List<PerMatchCredit> getPerMatchCreditList(String orderId, BigDecimal coreBalance) throws Exception{
		List<PerMatchCredit> rtnList = new ArrayList<PerMatchCredit>();

		//根据签约中金额，以5000为一隔断，得到预匹配标的个数 
		Integer matchedCount = getPreMatchCount(coreBalance);
		//根据签约中金额、预匹配标的个数得到预匹配金额数组
		BigDecimal[] arrayMatchAmout = getPreMatchAmountArray(coreBalance, matchedCount);
		//从预匹配金额数组得到预匹配金额最大值
		BigDecimal maxAmount = arrayMatchAmout[arrayMatchAmout.length - 1];
		//查询预匹配标的表列表
		PreMatchLoan preMatchLoan = new PreMatchLoan();
		//preMatchLoan.setMatchCount(matchedCount + 1);
		//2.0修改，设置最大匹配10条记录
		preMatchLoan.setMatchCount(10);
		preMatchLoan.setMaxAmount(maxAmount);
		
		//根据余额随机获取预匹配标的
		List<PreMatchLoan> preMatchLoanList = this.perMatchDao.getPreMatchLoanByOrderBalance(preMatchLoan);
		
		if(preMatchLoanList == null || preMatchLoanList.size()==0){
			logger.debug("订单查询预匹配标的列表失败！");
		}else{			
			for (int i = 0; i < preMatchLoanList.size(); i++) {
				PreMatchLoan preLoan = preMatchLoanList.get(i);
				PerMatchCredit perMatchCredit = new PerMatchCredit();
				perMatchCredit.setOrderId(Integer.valueOf(orderId));//订单id
				perMatchCredit.setLoanTitle(preLoan.getLoanTitle());//借款标题
				perMatchCredit.setLoanMonths(preLoan.getLoanMonths());//借款期限
				perMatchCredit.setResidualPeriods(preLoan.getLoanMonths());//剩余期数
				perMatchCredit.setInterest(preLoan.getInterest());//利率
				if(i<arrayMatchAmout.length){
					perMatchCredit.setCreditAmount(arrayMatchAmout[i]);//出借金额
				}else{
					perMatchCredit.setCreditAmount(arrayMatchAmout[arrayMatchAmout.length-1]);//出借金额
				}
				perMatchCredit.setIncomePrincipal(BigDecimal.ZERO);//已收本金
				perMatchCredit.setIncomeInterest(BigDecimal.ZERO);//已收利息
				perMatchCredit.setOrderState("1");//交易状态：预匹配
				perMatchCredit.setUserId(preLoan.getBorrowerId());//所属用户
				perMatchCredit.setBorrowName(preLoan.getBorrowName());//借款人名称
				perMatchCredit.setContactAmount(preLoan.getContactAmount());//标的借款金额
				
				//保存预匹配债权信息
				this.perMatchDao.insertPerMatchCrdit(perMatchCredit);
				
				rtnList.add(perMatchCredit);
			}
		}
		
		return rtnList;
	}
	
	/**
	 * 根据签约中金额，以5000为一隔断，得到预匹配标的个数 
	 * @param amount
	 * @return
	 */
	private static Integer getPreMatchCount(BigDecimal amount){
		//BigDecimal num1 = new BigDecimal("19000.00");
		BigDecimal num2 = new BigDecimal("5000.00");
		//返回其值为(this % divisor)的BigDecimal。 
		BigDecimal remain = amount.remainder(num2);
		int count = 0;
		if(remain.compareTo(BigDecimal.ZERO)==0){
//			log.info("整除");
			count = amount.divide(num2).intValue();
		}else{
			count = amount.subtract(remain).divide(num2).intValue()+1;
		}
//		log.info("个数 "+count);
		return count;
	}
	
	/**
	 * 根据签约中金额、预匹配标的个数得到预匹配金额数组
	 * @param amount 签约中金额 作为 预匹配金额
	 * @param count 预匹配标的个数
	 * @return 预匹配金额数组
	 */
	private static BigDecimal[] getPreMatchAmountArray(BigDecimal amount,Integer count){
		//定义固定长度数组
		BigDecimal[] array = new BigDecimal[count];
		//取余数，得到 签约中金额与预匹配标的个数的 余数
		BigDecimal remain = amount.remainder(new BigDecimal(count));
//		log.info("余数 "+remain);
		//得到平均值，（预匹配金额-余数）/预匹配标的个数 = 平均值
		BigDecimal avg = amount.subtract(remain).divide(new BigDecimal(count));
		//循环数组，预匹配数组前面放入平均值，最后一个放入（平均值+余数）
		for (int i = 0; i < count; i++) {
			if(i != count - 1){
				array[i] = avg;
//				System.out.println(array[i]);
			}else{
				array[i] = avg.add(remain);
//				System.out.println(array[i]);
			}
		}
		return array;
	}


}
